<?php // content="text/plain; charset=utf-8"
require_once ('jpgraph/jpgraph.php');
require_once ('jpgraph/jpgraph_scatter.php');
require_once ('jpgraph/jpgraph_line.php');
require_once ('jpgraph/jpgraph_utils.inc.php');

require_once 'db_utility.php';
require_once ('visibility.php');

$visibility1 = $_GET['visibility1'];
$visibility2 = $_GET['visibility2'];

$conn = db_connect();
$asso = array();

// get ranks for each story from popularity interface
$story_table_name = get_story_table_name($visibility1);
$strsql="SELECT * FROM $story_table_name order by popularity desc";
$result = $conn->query($strsql);

if (!$result) {
	die('Could not query:' . mysql_error());
}
$i=0;
while($row = $result->fetch_assoc()){
	$story_id = $row['story_id'];
	$asso[$story_id] = array($i);
	$i++;
}
$result->close();

// get ranks for each story from random interface
$story_table_name = get_story_table_name($visibility2);
$strsql="SELECT * FROM $story_table_name order by popularity desc";
$result = $conn->query($strsql);

if (!$result) {
	die('Could not query:' . mysql_error());
}
$i=0;
while($row = $result->fetch_assoc()){
	$story_id = $row['story_id'];
	array_push($asso[$story_id], $i);
	$i++;
}

$result->close();
$conn->close();


$datax = array();
$datay = array();
foreach ($asso as $storyId => $pair) {
	array_push($datay, $pair[0]); // popularity
	array_push($datax, $pair[1]); // random
}

$lr = new LinearRegression($datax, $datay);
list( $stderr, $corr ) = $lr->GetStat();
list( $xd, $yd ) = $lr->GetY(0,50);
 
// Create the graph
$graph = new Graph(500,250);
$graph->SetScale('linlin');
 
// Setup title
$graph->title->Set("Correlation\n(Y: # rank in $visibility1 interface)\n(X: # rank in $visibility2 interface)");
$graph->title->SetFont(FF_ARIAL,FS_BOLD,14);

$graph->subtitle->Set('(stderr='.sprintf('%.2f',$stderr).', corr='.sprintf('%.2f',$corr).')');
$graph->subtitle->SetFont(FF_ARIAL,FS_NORMAL,12);

// make sure that the X-axis is always at the
// bottom at the plot and not just at Y=0 which is
// the default position
$graph->xaxis->SetPos('min');
 
// Create the scatter plot with some nice colors
$sp1 = new ScatterPlot($datay,$datax);
$sp1->mark->SetType(MARK_FILLEDCIRCLE);
$sp1->mark->SetFillColor("red");
$sp1->SetColor("blue");
$sp1->SetWeight(3);
$sp1->mark->SetWidth(4);
 
// Create the regression line
$lplot = new LinePlot($yd);
$lplot->SetWeight(2);
$lplot->SetColor('navy');
 
// Add the pltos to the line
$graph->Add($sp1);
$graph->Add($lplot);
 
// ... and stroke
$graph->Stroke();
 
?>